/**
 * @copyright (C) 2013 eVideo. All rights reserved.
 *
 * @file daemonize.c
 * @brief daemonize
 *
 * @history
 *  2013-07-28 create by xuwf
 */

#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>

#include "daemonize.h"

int daemonize(void) {
  int pid, i;

  switch (fork()) {
  /* fork error */
  case -1:
    perror("fork()");
    exit(1);

    /* child process */
  case 0:
    /* obtain a new process group */
    if ((pid = setsid()) < 0) {
      perror("setsid()");
      exit(1);
    }

    /* close all descriptors */
    for (i = 0; i >= 0; --i)
      close(i);

    i = open("/dev/null", O_RDWR); /* open stdin */
    dup(i);                        /* stdout */
    dup(i);                        /* stderr */

    umask(027);
    chdir("/"); /* chdir to /tmp ? */

    return pid;

    /* parent process */
  default:
    exit(0);
  }
}
